import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_manager/photo_manager.dart';

class AssetPathEntityAdapter {
  AssetPathEntity assetPath;
  AssetEntity previewAsset;
  int assetCount;

  AssetPathEntityAdapter(
      {required this.assetPath,
      required this.previewAsset,
      required this.assetCount});
}

class GalleryPhotoProvider extends ChangeNotifier {
  List<AssetPathEntityAdapter> pathAdapterList = [];
  AssetPathEntityAdapter? pathAdapter;
  List<AssetEntity> assetList = [];
  Map<String, AssetEntity> selectedAssetMap = {};
  AssetEntity? currentPreviewAsset;
  bool working = false;
  int assetPage = 0;
  int assetPageCount = 50;

  chosePreviewAsset(AssetEntity previewAsset) {
    currentPreviewAsset = previewAsset;
    notifyListeners();
  }

  clearSelectAssets() {
    selectedAssetMap.clear();
    notifyListeners();
  }

  initDataBase() async {
    await AppAssetTransProvider.provider().inpectAssetTransStatus();
    notifyListeners();
  }

  triggerCollectAsset(AssetEntity? asset) {
    if (currentPreviewAsset == null) return;
    if (asset == null) return;
    AssetEntity selectedAsset = asset;
    if (selectedAssetMap[selectedAsset.id] != null) {
      selectedAssetMap.remove(selectedAsset.id);
      notifyListeners();
      return;
    }
    if (selectedAssetMap.keys.isNotEmpty) {
      if (selectedAssetMap[selectedAssetMap.keys.last]!.type ==
              AssetType.video &&
          asset.type == AssetType.video) {
        EasyLoading.showToast(appLocal().onlyCanOneVideoSendOnce);
        return;
      }
      if (selectedAssetMap[selectedAssetMap.keys.last]!.type ==
              AssetType.video &&
          asset.type != AssetType.video) {
        EasyLoading.showToast(appLocal().pictureAndVideoCantSendAtSameTime);
        return;
      }
      if (selectedAssetMap[selectedAssetMap.keys.last]!.type !=
              AssetType.video &&
          asset.type == AssetType.video) {
        EasyLoading.showToast(appLocal().pictureAndVideoCantSendAtSameTime);
        return;
      }
    }
    if (asset.type == AssetType.video && asset.duration > 60 * 5) {
      EasyLoading.showToast(appLocal().videoTooLong);
      return;
    }
    selectedAssetMap[selectedAsset.id] = selectedAsset;
    notifyListeners();
  }

  bool containAsset(String assetId) {
    return selectedAssetMap[assetId] != null;
  }

  num assetPosition(String assetId) {
    return selectedAssetMap.keys.toList().indexOf(assetId);
  }

  refreshAssetPath() async {
    if (working) return;
    working = true;
    List<AssetPathEntity> list = await PhotoManager.getAssetPathList();
    List<AssetPathEntityAdapter> buffer = [];
    for (AssetPathEntity e in list) {
      int count = await e.assetCountAsync;
      if (count > 0) {
        AssetEntity preview =
            (await e.getAssetListPaged(page: 0, size: 1)).first;
        buffer.add(AssetPathEntityAdapter(
            assetPath: e, previewAsset: preview, assetCount: count));
      }
    }
    working = false;
    if (buffer.isNotEmpty) {
      pathAdapterList.clear();
      pathAdapterList.addAll(buffer);
      if (pathAdapter == null) {
        pathAdapter = pathAdapterList.first;
      } else {
        for (AssetPathEntityAdapter e in pathAdapterList) {
          if (pathAdapter!.assetPath.id == e.assetPath.id) {
            pathAdapter = e;
            break;
          }
        }
      }
      notifyListeners();
    }
  }

  updateAssetPath(String assetPathId) async {
    if (working) return;
    working = true;
    for (AssetPathEntityAdapter e in pathAdapterList) {
      if (e.assetPath.id == assetPathId) {
        pathAdapter = e;
        break;
      }
    }
    working = false;
    refreshAssets();
  }

  refreshAssets() async {
    if (working) return;
    working = true;
    if (pathAdapter == null) {
      working = false;
      return;
    }
    assetPage = 0;
    List<AssetEntity> list = await pathAdapter!.assetPath
        .getAssetListPaged(page: assetPage, size: assetPageCount);
    assetList.clear();
    assetList.addAll(list);
    if (currentPreviewAsset == null || currentPreviewAsset?.id == null) {
      currentPreviewAsset = assetList.first;
    } else {
      currentPreviewAsset = await AssetEntity.fromId(currentPreviewAsset!.id);
      currentPreviewAsset ??= assetList.first;
    }
    working = false;
    notifyListeners();
  }

  loadMoreAssets() async {
    if (working) return;
    working = true;
    if (pathAdapter == null) {
      working = false;
      return;
    }
    if (assetList.length >= pathAdapter!.assetCount) {
      working = false;
      return;
    }
    List<AssetEntity> list = await pathAdapter!.assetPath
        .getAssetListPaged(page: ++assetPage, size: assetPageCount);
    assetList.addAll(list);
    working = false;
    notifyListeners();
  }

  requestPermission() async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    return ps.hasAccess;
  }

  bool hasSendAsset(String assetId) {
    return AppAssetTransProvider.provider().allAssetIds.contains(assetId);
  }
}
